package com.ylsk.check.service.impl;

import com.google.common.collect.Maps;
import com.google.common.primitives.Longs;
import com.ylsk.check.domain.*;
import com.ylsk.check.domain.dto.EntryReportDTO;
import com.ylsk.check.domain.dto.JeevesReportDTO;
import com.ylsk.check.domain.dto.MsgTemplateDTO;
import com.ylsk.check.domain.dto.WithdrawalReportDTO;
import com.ylsk.check.domain.emum.ConstructionStatusEnum;
import com.ylsk.check.domain.so.JeevesReportSO;
import com.ylsk.check.domain.vo.JeevesReportVO;
import com.ylsk.check.mapper.*;
import com.ylsk.common.config.SnowIdConfig;
import com.ylsk.common.core.domain.entity.SysUser;
import com.ylsk.common.exception.ServiceException;
import com.ylsk.common.utils.Generic;
import com.ylsk.system.domain.SysMsg;
import com.ylsk.system.service.ISysConfigService;
import com.ylsk.system.service.ISysMsgService;
import com.ylsk.system.service.ISysUserService;
import io.jsonwebtoken.lang.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Component

public class ReportInfoHelper {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ReportInfoMapper reportInfoMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysMsgService sysMsgService;

    @Autowired
    private EntryReportMapper entryReportMapper;

    @Autowired
    private JeevesReportMapper jeevesReportMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private CheckTaskMapper checkTaskMapper;

    @Autowired
    private SnowIdConfig snowIdConfig;
    /**
     * 施工管理员角色id
     */
    public static final Long DATA_MANAGER_ROLE_ID = 102L;

    /**
     * 分管领导角色id
     */
    public static final Long DEPT_LEADER_ROLE_ID = 103L;

    /**
     * 获取项目报备信息
     * @param reportInfoId
     * @return
     */
    public ReportInfo getReportInfo(Long reportInfoId){
        if(null == reportInfoId){
            throw new ServiceException("项目报备id不能为空!");
        }
        ReportInfo reportInfo = reportInfoMapper.selectById(reportInfoId);
        if(null == reportInfo){
            throw new ServiceException(String.format("业务数据不存在,reportInfoId=【%1$s】",reportInfoId));
        }
        return reportInfo;
    }

    /**
     * 更新施工状态
     * @param reportInfo
     * @param constructionStatusEnum
     * @return
     */
    public int updateReportConstructionStatus(ReportInfo reportInfo, ConstructionStatusEnum constructionStatusEnum){

        if(null == constructionStatusEnum){
            throw new ServiceException("施工状态不能为空!");
        }
        logger.info("更新施工状态:" + constructionStatusEnum.getRemark());
        reportInfo.setConstructionStatus(constructionStatusEnum.getCode());
        return reportInfoMapper.updateById(reportInfo);
    }


    public List<SysUser> getDeptLeader(Long deptId){
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(deptId);
        List<Long> roleIds = Longs.asList(DATA_MANAGER_ROLE_ID,DEPT_LEADER_ROLE_ID);
        sysUser.setRoleIds(roleIds.toArray(new Long[roleIds.size()]));
        List<SysUser> sysUserList = sysUserService.selectUserListByDeptIdAndRoleIds(sysUser);
        return sysUserList;
    }

    /**
     * 获取人员信息
     * @param userId
     * @return
     */
    public SysUser getUserInfo(Long userId){
        if(null == userId){
            throw new ServiceException("参数异常!");
        }
        SysUser sysUser = sysUserService.selectUserById(userId);
        return sysUser;
    }
    /**
     * 获取当前部门 下面的 施工管理员信息
     * @param deptId
     * @return
     */
    public SysUser getDeptDataManager(Long deptId){
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(deptId);
        sysUser.setRoleId(DATA_MANAGER_ROLE_ID);
        List<SysUser> sysUserList = sysUserService.selectUserListByDeptIdAndRoleId(sysUser);
        if(CollectionUtils.isEmpty(sysUserList) ||sysUserList.size() == 0 ){
            return null;
        }
        return sysUserList.get(0);
    }

    /**
     * 是否开启发送短信
     * @return
     */
    public boolean enableSendMsg(){
        return configService.selectSendMsgEnabled();
    }
    /**
     * 保存消息
     * @param msgTemplateDTO
     * @param parameters
     */
    public void saveMsg(MsgTemplateDTO msgTemplateDTO, Object...parameters){
        List<Long> toUser = msgTemplateDTO.getToUser();
        if(CollectionUtils.isEmpty(toUser)){
            return;
        }

        for (int i = 0; i < toUser.size(); i++) {
            String template = msgTemplateDTO.getMsgTemplateEnum().getTemplate();
            String msg = String.format(template, parameters);
            SysMsg sysMsg = new SysMsg();
            sysMsg.setFromUser(msgTemplateDTO.getFrommUser());
            sysMsg.setFromTime(new Date());
            sysMsg.setToUser(toUser.get(i));
            sysMsg.setTitle(msgTemplateDTO.getMsgTemplateEnum().getTitle());
            sysMsg.setMessage(msg);
            sysMsgService.insertSysMsg(sysMsg);
        }
    }

    /**
     * 进场上报，占道上报，撤场上报 需要写入任务表
     * @param reportInfoId
     * @param constructionStatus
     * @param tbName
     * @param reportBusinessId
     * @param execTime
     */
    public void saveTask(Long reportInfoId,int constructionStatus,String tbName,Long reportBusinessId,Date execTime,Long deptId){
        CheckTask checkTask = new CheckTask();
        checkTask.setCheckTaskId(snowIdConfig.getSnowId());
        checkTask.setReportInfoId(reportInfoId);
        checkTask.setConstructionStatus(constructionStatus);
        checkTask.setTbName(tbName);
        checkTask.setReportBusinessId(reportBusinessId);
        checkTask.setExecTime(execTime);
        checkTask.setDeptId(deptId);
        checkTask.setTaskStatus(0);//任务状态未检查
        checkTaskMapper.insert(checkTask);
    }


    /**
     * 校验工程数据
     * @param reportInfo
     * @param generic
     */
    public void checkData(ReportInfo reportInfo, Generic generic ){
        //if(!configService.selectCheckReportEnabled()) return;
        Object key = generic.getKey();
        Map<String,Object> map = Maps.newHashMap();
        map.put("report_info_id",reportInfo.getReportInfoId());
        final Integer reportStatus = reportInfo.getConstructionStatus();
        if(key instanceof EntryReportDTO){
            /****
             * 进场上报
             * 进场上报只能上报一次
             * 工程状态只有等于未进场才能进场上报操作
             */
            if(reportStatus != ConstructionStatusEnum.NOT_ENTERY.getCode()){
                throw new ServiceException(String.format("当前工程状态处于%s中,不能进行进场上报操作!",ConstructionStatusEnum.getDesc(reportStatus)));
            }
            List<EntryReport> entryReportList = entryReportMapper.selectByMap(map);
            if(!Collections.isEmpty(entryReportList)){
                throw new ServiceException("当前工程已提交过进场上报数据,不允许再次提交!");
            }
        }else if(key instanceof JeevesReportDTO){

        }else if(key instanceof WithdrawalReportDTO){

        }else{
            throw new ServiceException("类型不匹配,操作失败!");
        }
    }
}
